package cn.congine.wizarpos.mall.weChat;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.AccessTokenOutput;
import cn.congine.wizarpos.mall.model.open.AccessTokenOutput.Result;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.weChat.bussiness.WechartCoreService;
import cn.congine.wizarpos.mall.weChat.util.MessageUtil;
import cn.congine.wizarpos.mall.weChat.util.SignUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "/wechat")
public class WeChatction {

	private static Logger log = LoggerFactory.getLogger(WeChatction.class);

	public static final String ServiceURL = "/entry";
	public static final String CreateMenu = "/createMenu";

	@Autowired
	private WechartCoreService wechartCoreService;
	
	@Resource(name = "messageSource")
	private MessageSource messageSource;
	@Autowired
	private WPosHttpClient wposHttpClient;
	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;	
	
	@RequestMapping(value = ServiceURL)
	public void wechatEntryPoint(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		
		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (echostr != null && SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		} else {
			out.print("");
			try {
				String respMessage = wechartCoreService.processRequest(request, response);
			
				out.print(respMessage);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		IOUtils.closeQuietly(out);
		
	}

	/**
	 * 创建公众号菜单
	 * @param appid
	 * @param accessToken
	 * @param type 商户类型 1零售 2餐饮 3服务
	 * @param mid
	 */
	@RequestMapping(value = CreateMenu)
	public String createMenu(String mid) {
		String type = null;
		String appid = null;		
		// 商户数据
		MerchantDefQueryInput input = new MerchantDefQueryInput();
		input.setMid(mid);
		MerchantDefQueryOutput output = (MerchantDefQueryOutput) wizarposOpenRestClient.post(input, "/merchantdef/info", MerchantDefQueryOutput.class);		
		if (output == null || !SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			log.error("请求开放平台获取商户信息失败");
		} else {
			MerchantDef merchantDef = output.getResult();
			type = merchantDef.getMerchantType();
			appid = merchantDef.getWeixinAppId();
		}		
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		AccessTokenOutput jsOutput = (AccessTokenOutput) wizarposOpenRestClient.post(jsInput, "/weixin/accesstoken", AccessTokenOutput.class);		
		String accessToken = null;
		if (jsOutput != null && SysConstants.OPEN_SUCCESS.equals(jsOutput.getCode())) {
			Result apiTicket = jsOutput.getResult();
			if (apiTicket != null) {
				accessToken = apiTicket.getToken();
			} else {
				log.error("create menu fial, access token is null");
				return "create menu fial, access token is null";
			}
		} else {
			log.error("create menu fial, access token is null");
			return "create menu fial, access token is null";
		}

		String url = SysConstants.MENU_CREATE_URL.replace(SysConstants.ACCESS_TOKEN, accessToken);
		String dns = messageSource.getMessage(SysConstants.SERVICE_DNS, null,Locale.ENGLISH);
		
		JSONArray button = new JSONArray();
		if ("1".equals(type)) { // 零售类菜单
			JSONObject card = new JSONObject();
			card.put("type", "view");
			card.put("name", "会员卡");
			card.put("url",	"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns 
							+ "%2fwizarpos-mall-sole%2foauth%2fcards&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");

			JSONObject shop = new JSONObject();
			shop.put("type", "view");
			shop.put("name", "微店");
			shop.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fshelf&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");

			JSONArray my = new JSONArray();
			JSONObject order = new JSONObject();
			order.put("type", "view");
			order.put("name", "订单");
			order.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2forders&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			my.add(order);
			JSONObject shopChat = new JSONObject();
			shopChat.put("type", "view");
			shopChat.put("name", "购物车");
			shopChat.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fshopping_cart&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			my.add(shopChat);
			JSONObject quan = new JSONObject();
			quan.put("type", "view");
			quan.put("name", "提货券");
			quan.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fvouchers&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			my.add(quan);
			
			JSONObject mrt = new JSONObject();
			mrt.put("type", "view");
			mrt.put("name", "门店介绍");
			mrt.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fmerchant_info&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			my.add(mrt);
			
			JSONObject mymenu = new JSONObject();
			mymenu.put("name", "我的");
			mymenu.put("sub_button", my);

			button.add(card);
			button.add(shop);
			button.add(mymenu);
		} else if ("2".equals(type)) { // 餐饮类菜单
			JSONArray makeAnOrder = new JSONArray();//我要订餐
			JSONObject yuding = new JSONObject();
			yuding.put("type", "view");
			yuding.put("name", "我要预订");
			yuding.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fyuding&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");			
			makeAnOrder.add(yuding);
			
			JSONObject jsutInTime = new JSONObject();//即时点单
			jsutInTime.put("type", "view");
			jsutInTime.put("name", "即时点单");
			jsutInTime.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fcatering&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			makeAnOrder.add(jsutInTime);
			
			JSONObject takeout = new JSONObject();
			takeout.put("type", "view");
			takeout.put("name", "来份外卖");
			takeout.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2ftakeout&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			makeAnOrder.add(takeout);
			
			JSONObject hujiao = new JSONObject();
			hujiao.put("type", "view");
			hujiao.put("name", "呼叫服务");
			hujiao.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fhujiao&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			makeAnOrder.add(hujiao);	
			
			
			JSONObject ordermenu = new JSONObject();//我要订餐
			ordermenu.put("name", "我要订餐");
			ordermenu.put("sub_button", makeAnOrder);			
						
			JSONObject scan2menu = new JSONObject();
			scan2menu.put("type", "view");
			scan2menu.put("name", "扫一扫");
			scan2menu.put("url",	"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns 
							+ "%2fwizarpos-mall-sole%2foauth%2fscan2menu&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");

			JSONArray my = new JSONArray();//我的
			JSONObject myReOrder = new JSONObject();
			myReOrder.put("type", "view");
			myReOrder.put("name", "预订单");
			myReOrder.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fcatering_re_list&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			my.add(myReOrder);
					
			JSONObject myOrder = new JSONObject();
			myOrder.put("type", "view");
			myOrder.put("name", "订单");
			myOrder.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fcatering_list&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			my.add(myOrder);

			JSONObject card = new JSONObject();
			card.put("type", "view");
			card.put("name", "会员卡");
			card.put("url", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
							+ "&redirect_uri=http%3a%2f%2f" + dns
							+ "%2fwizarpos-mall-sole%2foauth%2fcards&response_type=code&scope=snsapi_base&state="
							+ mid + "#wechat_redirect");
			my.add(card);			
			JSONObject mymenu = new JSONObject();
			mymenu.put("name", "我的");
			mymenu.put("sub_button", my);
			
			button.add(ordermenu);
			button.add(scan2menu);
			button.add(mymenu);
		} else if ("3".equals(type)) {
			// 服务类菜单 待定
		}
		JSONObject menus = new JSONObject();
		menus.put("button", button);
		log.debug(menus.toString());

		// 调用接口创建菜单
		JSONObject result = null;
		try {
			result = wposHttpClient.post(url, menus);
		} catch (Exception e) {
			log.debug(e.getMessage());
			if (log.isDebugEnabled()) {
				e.printStackTrace();
			}
		}
		
		if (result != null && result.getIntValue("errcode") != 0) {
			log.debug("create menu result: " + result);
			return "create menu result:" + result;
		}
		
		return "create menu result: error" ;
	}

}

